package net.shizhibao.www.mylibrary;


import android.annotation.SuppressLint;
import android.text.TextUtils;

import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * Created by  on 2019/2/22.
 * desc:使webview支持window.history.go()
 * 使用webview.goBack替换js中的history.go()方法
 */
public class WebViewGoBackSupport {

    /**
     * 自定义的，当js调用history.go时加载的链接，以监听history.go方法的调用
     */
    private final static String CONSTANTS_GO_BACK = "/CONSTANTS_GO_BACK#";
    /**
     * 当webview不能在返回时回调的方法
     */
    @Nullable
    private Runnable whenCannotGoBackRunnable;
    @NonNull
    private WebView webview;

    /**
     * @param whenCannotGoBackRunnable 当没有上一个页面，而js调用了history.go时回调的方法
     */
    @SuppressLint("SetJavaScriptEnabled")
    public WebViewGoBackSupport(@NonNull WebView webview, @Nullable Runnable whenCannotGoBackRunnable) {
        this.webview = webview;
        this.whenCannotGoBackRunnable = whenCannotGoBackRunnable;
        this.webview.getSettings().setJavaScriptEnabled(true);
    }

    /**
     * @param whenCannotGoBackRunnable 当没有上一个页面，而js调用了history.go时回调的方法
     * @param defaultClient            true时，不需要手动调用 onPageFinished、shouldOverrideUrlLoading
     */
    public WebViewGoBackSupport(@NonNull WebView webview, @Nullable Runnable whenCannotGoBackRunnable, boolean defaultClient) {
        this(webview, whenCannotGoBackRunnable);
        if (defaultClient) {
            webview.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    WebViewGoBackSupport.this.onPageFinished(url);
                    super.onPageFinished(view, url);
                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    WebViewGoBackSupport.this.shouldOverrideUrlLoading(url);
                    return super.shouldOverrideUrlLoading(view, url);
                }
            });
        }
    }

    /**
     * 在WebViewClient对应方法中调用
     * 注：此方法需手动调用，或者使用defaultClient == true
     */
    public void onPageFinished(String url) {
        //重写js页面window.history.go方法
        String script = "javascript:(function(){window.history.go = function(index){" +
                "window.location.href='" + CONSTANTS_GO_BACK + "'+index;" +
                "}})()";
        webview.loadUrl(script);
    }

    /**
     * 在WebViewClient对应方法中调用
     * 注：此方法需手动调用，或者使用defaultClient == true
     */
    public void shouldOverrideUrlLoading(String url) {
        if (!TextUtils.isEmpty(url) && url.contains(CONSTANTS_GO_BACK)) {
            int step = -1;
            try {
                //解析js调用history.go时传入的参数
                step = Integer.parseInt(url.split("#")[1]);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (webview.canGoBackOrForward(step)) {
                webview.goBackOrForward(step);
            } else if (whenCannotGoBackRunnable != null) {
                //当没有上一个页面，而js调用了history.go时回调方法
                whenCannotGoBackRunnable.run();
            }
        }
    }
}